<template>
  <div class="search">
    <!-- 顶端搜索框 -->
    <!-- form标签添加了并且action不为空，ios输入框会呈现搜索按钮 -->
    <form action="/" class="searchForm">
      <van-search
        v-model.lazy="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="onFocus"
      />
    </form>

    <!-- 搜索历史，结果，建议组件 -->
    <!-- 结果 -->
    <resulte v-if="isResultShow" :searchText="searchText"></resulte>
    <!-- 历史 -->
    <history v-else-if="!searchText" @searchRult="onSearch"></history>
    <!-- 建议 -->
    <suggestion v-else :suggestText="searchText" @searched="onSearch"></suggestion>
  </div>
</template>

<script>
// 注册搜索建议，历史，结果
import history from './conponents/history.vue'
import suggestion from './conponents/suggestion.vue'
import resulte from './conponents/resulte.vue'
export default {
  name: 'search',
  data() {
    return {
      // 搜索输入框的数据
      searchText: '',
      // 控制搜索结果的展示
      isResultShow: false
    }
  },
  methods: {
    // 搜索框的搜索事件, // 搜索建议提交结果统一了
    onSearch(val) {
      // 如果搜索值为空则不继续执行
      if (!val) {
        return false
      }
      this.searchText = val
      this.isResultShow = true
    },
    // 搜索框的取消事件
    onCancel() {
      this.$router.back()
    },
    onFocus() {
      this.isResultShow = false
    }
  },
  components: {
    history,
    suggestion,
    resulte
  }
}
</script>

<style lang="less" scoped>
.searchForm {
  /deep/ .van-search {
    background-color: #3296fa;
    .van-search__content {
      border-radius: 7px;
    }
    .van-search__action {
      color: #fff;
    }
  }
}
</style>
